<template>
  <div class="photography-detail-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6" v-loading="loading">
        <div class="flex flex-col space-y-4">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="text-sm">
            <el-breadcrumb-item :to="{ path: '/photography' }"
              >摄影打卡</el-breadcrumb-item
            >
            <el-breadcrumb-item>{{ spotDetail.name }}</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 标题和操作按钮 -->
          <div class="flex items-center justify-between">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white line-clamp-1 flex-1 mr-4"
            >
              {{ spotDetail.name }}
            </h1>
            <div class="flex items-center gap-3">
              <el-button-group>
                <el-button
                  type="primary"
                  plain
                  :icon="Share"
                  @click="handleShare"
                  >分享</el-button
                >
                <el-button
                  :type="spotDetail.isFavorited ? 'primary' : 'default'"
                  plain
                  :icon="Star"
                  @click="handleFavorite"
                >
                  {{ spotDetail.isFavorited ? "已收藏" : "收藏" }}
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 打卡地详情 -->
          <div
            class="spot-content bg-white dark:bg-gray-800 rounded-lg shadow-sm"
          >
            <!-- 基本信息 -->
            <div class="border-b border-gray-100 dark:border-gray-700 p-6">
              <div class="flex items-center gap-6">
                <el-tag
                  :type="getTagType(spotDetail.type)"
                  effect="light"
                  size="large"
                >
                  {{ spotDetail.type }}
                </el-tag>
                <div
                  class="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Timer /></el-icon>
                    最佳拍摄：{{ spotDetail.bestTime }}
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Camera /></el-icon>
                    {{ formatNumber(spotDetail.checkInCount) }}次打卡
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Picture /></el-icon>
                    {{ formatNumber(spotDetail.photoCount) }}张照片
                  </span>
                </div>
              </div>
            </div>

            <!-- 主图展示 -->
            <div class="p-6">
              <el-carousel
                :height="'400px'"
                :autoplay="true"
                indicator-position="outside"
                class="rounded-lg overflow-hidden"
              >
                <el-carousel-item
                  v-for="image in spotDetail.images || []"
                  :key="image"
                >
                  <el-image
                    :src="image"
                    fit="cover"
                    class="w-full h-full"
                    :preview-src-list="spotDetail.images"
                  />
                </el-carousel-item>
                <!-- 如果没有图片，显示默认图片 -->
                <el-carousel-item v-if="!(spotDetail.images && spotDetail.images.length)">
                  <el-image
                    :src="spotDetail.image || 'https://images.pexels.com/photos/346885/pexels-photo-346885.jpeg'"
                    fit="cover"
                    class="w-full h-full"
                  />
                </el-carousel-item>
              </el-carousel>
            </div>

            <!-- 打卡地介绍 -->
            <div class="p-6">
              <h2 class="flex items-center text-xl font-bold text-gray-900 dark:text-white mb-4">
                <el-icon class="mr-2 text-primary-500"><InfoFilled /></el-icon>
                打卡地介绍
              </h2>
              <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                <p class="text-gray-600 dark:text-gray-300 leading-relaxed">
                  {{ spotDetail.description }}
                </p>
              </div>
            </div>

            <!-- 拍摄指南 -->
            <div class="p-6 border-t border-gray-100 dark:border-gray-700">
              <h2
                class="flex items-center text-xl font-bold text-gray-900 dark:text-white mb-4"
              >
                <el-icon class="mr-2 text-primary-500"><Camera /></el-icon>
                拍摄指南
              </h2>

              <div class="space-y-6">
                <!-- 最佳时段 -->
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                  <h3
                    class="text-lg font-medium text-gray-900 dark:text-white mb-3 flex items-center"
                  >
                    <el-icon class="mr-2 text-primary-500"><Timer /></el-icon>
                    最佳拍摄时段
                  </h3>
                  <ul class="list-disc pl-5 text-gray-600 dark:text-gray-400 space-y-2">
                    <li v-if="spotDetail.shootingTip?.morningTip">清晨：{{ spotDetail.shootingTip.morningTip }}</li>
                    <li v-if="spotDetail.shootingTip?.eveningTip">黄昏：{{ spotDetail.shootingTip.eveningTip }}</li>
                    <li v-if="spotDetail.shootingTip?.nightTip">夜景：{{ spotDetail.shootingTip.nightTip }}</li>
                  </ul>
                </div>

                <!-- 设备建议 -->
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                  <h3
                    class="text-lg font-medium text-gray-900 dark:text-white mb-3 flex items-center"
                  >
                    <el-icon class="mr-2 text-primary-500"><Picture /></el-icon>
                    设备建议
                  </h3>
                  <ul class="list-disc pl-5 text-gray-600 dark:text-gray-400 space-y-2">
                    <li v-if="spotDetail.shootingTip?.cameraTip">相机：{{ spotDetail.shootingTip.cameraTip }}</li>
                    <li v-if="spotDetail.shootingTip?.lensTip">镜头：{{ spotDetail.shootingTip.lensTip }}</li>
                    <li v-if="spotDetail.shootingTip?.otherTip">其他：{{ spotDetail.shootingTip.otherTip }}</li>
                  </ul>
                </div>

                <!-- 角度建议 -->
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                  <h3
                    class="text-lg font-medium text-gray-900 dark:text-white mb-3 flex items-center"
                  >
                    <el-icon class="mr-2 text-primary-500"><Position /></el-icon>
                    推荐拍摄角度
                  </h3>
                  <ul class="list-disc pl-5 text-gray-600 dark:text-gray-400 space-y-2">
                    <li
                      v-for="angle in spotDetail.shootingAngles || []"
                      :key="angle.id"
                    >
                      {{ angle.description }}
                    </li>
                    <li v-if="!(spotDetail.shootingAngles?.length)">暂无角度建议</li>
                  </ul>
                </div>

                <!-- 注意事项 -->
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                  <h3
                    class="text-lg font-medium text-gray-900 dark:text-white mb-3 flex items-center"
                  >
                    <el-icon class="mr-2 text-primary-500"><Warning /></el-icon>
                    拍摄注意事项
                  </h3>
                  <ul class="list-disc pl-5 text-gray-600 dark:text-gray-400 space-y-2">
                    <li
                      v-for="note in spotDetail.shootingNotes || []"
                      :key="note.id"
                    >
                      {{ note.content }}
                    </li>
                    <li v-if="!(spotDetail.shootingNotes?.length)">请注意保护环境，不要随意破坏景区设施</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 关联景点 -->
          <div
            v-if="relatedSpot"
            class="related-spot bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center">
              <el-icon class="mr-2 text-primary-500"><Location /></el-icon>
              关联景点
            </h3>
            <div class="spot-info">
              <el-image
                :src="relatedSpot.coverImage || relatedSpot.image"
                class="w-full h-40 object-cover rounded-lg mb-4 shadow-sm"
              />
              <h4
                class="text-lg font-medium text-gray-900 dark:text-white mb-2"
              >
                {{ relatedSpot.name }}
              </h4>
              <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
                {{ relatedSpot.description }}
              </p>
              <el-button
                type="primary"
                block
                @click="$router.push(`/spots/${relatedSpot.id}`)"
              >
                查看景点详情
              </el-button>
            </div>
          </div>

          <!-- 精选作品 -->
          <div class="featured-works bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-medium text-gray-900 dark:text-white flex items-center">
                <el-icon class="mr-2 text-primary-500"><PictureFilled /></el-icon>
                精选作品
              </h3>
              <el-button type="primary" link @click="handleUpload">
                上传作品
              </el-button>
            </div>
            
            <!-- 精选作品列表 -->
            <div class="grid grid-cols-2 gap-3">
              <div
                v-for="photo in spotDetail.topWorks || []"
                :key="photo.id"
                class="photo-item group relative rounded-lg overflow-hidden cursor-pointer shadow-sm hover:shadow-md transition-all duration-300"
                @click="$router.push(`/photography/works/${photo.id}`)"
              >
                <el-image
                  :src="photo.imageUrl"
                  class="w-full aspect-square object-cover transition-transform duration-500 group-hover:scale-105"
                  :preview-src-list="[photo.imageUrl]"
                />
                <div
                  class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <div class="absolute bottom-0 left-0 right-0 p-2">
                    <div class="flex items-center justify-between text-white/80 text-xs">
                      <span class="flex items-center">
                        <el-icon class="mr-1"><ThumbsUp /></el-icon>
                        {{ formatNumber(photo.likes || 0) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 如果没有作品，显示提示 -->
            <div v-if="!(spotDetail.topWorks && spotDetail.topWorks.length)" class="text-center py-4">
              <el-empty description="暂无作品" :image-size="60">
                <el-button size="small" @click="handleUpload">上传作品</el-button>
              </el-empty>
            </div>
            
            <!-- 查看更多作品按钮 -->
            <div v-if="spotDetail.topWorks && spotDetail.topWorks.length > 0" class="mt-4 text-center">
              <el-button type="primary" plain size="small" @click="$router.push(`/photography/${spotDetail.id}/works`)">
                查看更多作品
              </el-button>
            </div>
          </div>

          <!-- 打卡地位置 -->
          <div
            class="spot-location bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2 text-primary-500"><Location /></el-icon>
              打卡地位置
            </h3>
            <p v-if="spotDetail.location?.address" class="text-gray-600 dark:text-gray-400 mb-4">
              {{ spotDetail.location.address }}
            </p>
            <div ref="mapContainer" class="map-container h-80 rounded-lg overflow-hidden mb-4 bg-gray-100 dark:bg-gray-700">
              <!-- 地图组件将在这里加载 -->
            </div>
            <el-button type="primary" plain block @click="openMapNavigation">
              <el-icon class="mr-1"><Guide /></el-icon>
              导航到这里
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <el-dialog
      v-model="showShareDialog"
      title="分享打卡地"
      width="360px"
      align-center
    >
      <div class="share-options grid grid-cols-4 gap-4">
        <div
          v-for="platform in sharePlatforms"
          :key="platform.name"
          class="share-item flex flex-col items-center cursor-pointer hover:text-primary-600 transition-colors p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50"
          @click="handleShareTo(platform)"
        >
          <el-icon :size="24" class="mb-2">
            <component :is="platform.icon" />
          </el-icon>
          <span class="text-sm">{{ platform.label }}</span>
        </div>
      </div>
      <div class="mt-6">
        <div class="flex items-center bg-gray-50 dark:bg-gray-700 rounded p-2">
          <input
            type="text"
            :value="generateShareUrl"
            class="flex-1 bg-transparent border-none outline-none text-sm"
            readonly
          />
          <el-button type="primary" link @click="copyShareUrl">
            复制链接
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 上传作品弹窗 -->
    <el-dialog v-model="showUploadDialog" title="上传作品" width="500px">
      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="上传照片">
          <el-upload
            class="upload-demo"
            drag
            action="/api/upload"
            multiple
            :limit="9"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip text-gray-500 dark:text-gray-400">
                支持 jpg/png 文件，单张不超过 5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="拍摄时间">
          <el-date-picker
            v-model="uploadForm.shootTime"
            type="datetime"
            placeholder="选择拍摄时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="拍摄器材">
          <el-input
            v-model="uploadForm.camera"
            placeholder="相机型号、镜头等信息"
          />
        </el-form-item>
        <el-form-item label="作品描述">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="分享拍摄心得、构图技巧等"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUpload"> 发布作品 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Timer,
  Camera,
  Picture,
  PictureFilled,
  Star,
  Share,
  Location,
  Position,
  Warning,
  Upload,
  UploadFilled,
  ThumbsUp,
  Guide,
  Sunny,
  CopyDocument,
  Wechat,
  Weibo,
  InfoFilled,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import service from "@/api/axios";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const showShareDialog = ref(false);
const showUploadDialog = ref(false);
const hasMorePhotos = ref(true);
const spotId = ref(route.params.id);

// 上传表单
const uploadForm = ref({
  shootTime: "",
  camera: "",
  description: "",
  files: [],
});

// 测试数据 - 打卡地详情
const testSpotDetail = {
  id: 1,
  name: "贵港江滨公园日出",
  type: "人气打卡地",
  bestTime: "清晨或黄昏",
  checkInCount: 2580,
  photoCount: 3650,
  description:
    "江滨公园沿江而建，是拍摄江景、日出的绝佳位置。清晨的薄雾与晚霞倒映在江面上，构成独特的景致。建议在日出前半小时到达，寻找最佳机位。",
  isFavorited: false,
  image: "https://images.pexels.com/photos/1761279/pexels-photo-1761279.jpeg",
  images: [
    "https://images.pexels.com/photos/417102/pexels-photo-417102.jpeg",
    "https://images.pexels.com/photos/1761279/pexels-photo-1761279.jpeg"
  ],
  location: {
    address: "贵港市港北区江滨路",
    latitude: 23.1167,
    longitude: 109.5978
  },
  shootingTip: {
    morningTip: "日出前30分钟到达，拍摄晨雾缭绕的江面",
    eveningTip: "日落前1小时，可拍摄金色晚霞",
    nightTip: "夜景灯光绚丽，适合长曝光",
    cameraTip: "全画幅相机，建议带三脚架",
    lensTip: "16-35mm广角、70-200mm长焦",
    otherTip: "偏振镜、ND减光镜",
  },
  shootingAngles: [
    { id: 1, description: "江边栈道正面视角", spotId: 1, sortOrder: 1 },
    { id: 2, description: "观景平台俯瞰视角", spotId: 1, sortOrder: 2 },
    { id: 3, description: "桥上远眺视角", spotId: 1, sortOrder: 3 },
  ],
  shootingNotes: [
    { id: 1, content: "清晨人流较少，设备注意防潮", spotId: 1, sortOrder: 1 },
    { id: 2, content: "建议携带三脚架保证画面稳定", spotId: 1, sortOrder: 2 },
    { id: 3, content: "注意查看天气预报选择晴朗天气", spotId: 1, sortOrder: 3 },
  ],
  relatedSpotId: 1,
  photos: [
    {
      id: 1,
      url: "https://images.pexels.com/photos/417102/pexels-photo-417102.jpeg",
      description: "江滨公园夜景",
      spotId: 1,
      isCover: true,
      sortOrder: 1
    },
    {
      id: 2,
      url: "https://images.pexels.com/photos/1761279/pexels-photo-1761279.jpeg",
      description: "江滨公园日景", 
      spotId: 1,
      isCover: false,
      sortOrder: 2
    },
  ],
  topWorks: [
    {
      id: 1,
      title: "晨曦中的江面",
      description: "拍摄于清晨，江面雾气缭绕，景色优美",
      imageUrl: "https://images.pexels.com/photos/1834399/pexels-photo-1834399.jpeg",
      userId: 1,
      username: "user1",
      nickname: "摄影爱好者",
      userAvatar: "https://xsgames.co/randomusers/assets/avatars/male/32.jpg",
      likes: 245,
      views: 789,
      spotId: 1,
      spotName: "贵港江滨公园",
      camera: "Sony A7R4",
      lens: "16-35mm F2.8",
      settings: "f/11, 1/30s, ISO 100",
      shootingTime: "2023-06-15T06:30:00",
      createdAt: "2023-06-15T12:45:30"
    },
    {
      id: 2,
      title: "日落金辉",
      description: "傍晚时分，金色的阳光洒在江面",
      imageUrl: "https://images.pexels.com/photos/3225531/pexels-photo-3225531.jpeg",
      userId: 2,
      username: "user2",
      nickname: "日落摄影师",
      userAvatar: "https://xsgames.co/randomusers/assets/avatars/female/22.jpg",
      likes: 198,
      views: 567,
      spotId: 1,
      spotName: "贵港江滨公园",
      camera: "Canon 5D Mark IV",
      lens: "24-70mm F2.8",
      settings: "f/8, 1/125s, ISO 200",
      shootingTime: "2023-06-10T17:45:00",
      createdAt: "2023-06-10T20:30:15"
    }
  ],
  rating: 4.8,
};

// 打卡地详情数据
const spotDetail = ref({ ...testSpotDetail });

// 分页参数
const photoParams = ref({
  page: 1,
  size: 12,
});

// 分享平台
const sharePlatforms = [
  { name: "weixin", icon: "Wechat", label: "微信" },
  { name: "weibo", icon: "Weibo", label: "微博" },
  { name: "qq", icon: "ChatDotRound", label: "QQ" },
  { name: "copy", icon: "CopyDocument", label: "复制链接" },
];

// 生成分享链接
const generateShareUrl = computed(() => {
  return `${window.location.origin}/photography/${spotDetail.value.id}`;
});

// 获取标签类型
const getTagType = (type) => {
  const categories = [
    { label: "人气打卡地", type: "danger" },
    { label: "网红打卡点", type: "warning" },
    { label: "新晋打卡地", type: "success" },
    { label: "自然风光", type: "info" },
    { label: "人文景观", type: "" },
  ];
  const category = categories.find((c) => c.label === type);
  return category?.type || "";
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 获取打卡地详情
const fetchSpotDetail = async () => {
  loading.value = true;
  try {
    const res = await service.get(`/public/photography/spots/${spotId.value}`);
    if (res.data) {
      console.log("打卡地详情:", res.data);
      spotDetail.value = res.data;
      
      // 如果有关联景点ID，则获取关联景点信息
      if (spotDetail.value.relatedSpotId) {
        fetchRelatedSpot(spotDetail.value.relatedSpotId);
      }
      
      // 添加图片数组，兼容轮播图组件
      if (spotDetail.value.photos && spotDetail.value.photos.length > 0) {
        spotDetail.value.images = spotDetail.value.photos.map(photo => photo.url);
      } else if (spotDetail.value.image) {
        spotDetail.value.images = [spotDetail.value.image];
      }
      
      // 如果地图已加载，则更新地图
      if (mapLoaded.value && map) {
        // 添加标记
        if (spotDetail.value.location && spotDetail.value.location.address) {
          searchSpotLocation(spotDetail.value.name, spotDetail.value.location.address);
        } else {
          // 如果没有地址信息，直接搜索景点名称
          searchSpotLocation(spotDetail.value.name, spotDetail.value.name);
        }
      } else {
        // 延迟初始化地图，确保DOM完全渲染
        setTimeout(() => {
          initMap();
        }, 800);
      }
    }
  } catch (error) {
    console.error('获取打卡地详情失败:', error);
    // 使用测试数据，保持原样
  } finally {
    loading.value = false;
  }
};

// 获取关联景点信息
const relatedSpot = ref(null);
const fetchRelatedSpot = async (spotId) => {
  try {
    const res = await service.get(`/public/spot/${spotId}`);
    if (res.data) {
      console.log("关联景点:", res.data);
      relatedSpot.value = res.data;
    } else {
      // 尝试通过列表接口获取
      const listRes = await service.get('/public/spot/list');
      if (listRes.data && listRes.data.content) {
        const spot = listRes.data.content.find(item => item.id === spotId);
        if (spot) {
          relatedSpot.value = spot;
        }
      }
    }
  } catch (error) {
    console.error('获取关联景点失败:', error);
    // 如果获取失败，使用一个默认值
    relatedSpot.value = {
      id: spotId,
      name: "关联景点",
      coverImage: "https://images.pexels.com/photos/346885/pexels-photo-346885.jpeg",
      description: "这是一个与摄影打卡地相关的景点，您可以点击查看详情。"
    };
  }
};

// 获取打卡地照片
const fetchSpotPhotos = async () => {
  try {
    const params = {
      page: photoParams.value.page,
      size: photoParams.value.size,
    };
    const res = await service.get(`/public/photography/spots/${spotId.value}/photos`, { params });
    
    if (res.data) {
      if (photoParams.value.page === 1) {
        spotDetail.value.photos = res.data;
      } else {
        spotDetail.value.photos = [...spotDetail.value.photos, ...res.data];
      }
      
      // 判断是否还有更多照片
      hasMorePhotos.value = res.data.length >= photoParams.value.size;
    }
  } catch (error) {
    console.error('获取打卡地照片失败:', error);
    if (photoParams.value.page > 1) {
      hasMorePhotos.value = false;
    }
  }
};

// 处理收藏
const handleFavorite = async () => {
  try {
    // 调用收藏API，需要认证
    const url = `/photography/spots/${spotId.value}/favorite`;
    const method = spotDetail.value.isFavorited ? 'delete' : 'post';
    
    await service[method](url);
    
    spotDetail.value.isFavorited = !spotDetail.value.isFavorited;
    ElMessage.success(spotDetail.value.isFavorited ? "收藏成功" : "已取消收藏");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 处理分享到具体平台
const handleShareTo = (platform) => {
  // 直接显示成功消息，不调用API
  ElMessage.success(`分享到${platform.label}`);
  showShareDialog.value = false;
};

// 复制分享链接
const copyShareUrl = async () => {
  try {
    await navigator.clipboard.writeText(generateShareUrl.value);
    ElMessage.success("链接已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 处理上传
const handleUpload = () => {
  showUploadDialog.value = true;
};

// 处理照片预览
const handlePreview = (file) => {
  console.log("preview", file);
};

// 处理照片移除
const handleRemove = (file, fileList) => {
  console.log("remove", file, fileList);
};

// 处理上传成功
const handleUploadSuccess = (response, file) => {
  console.log("success", response, file);
  uploadForm.value.files.push(file.response);
};

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 提交上传
const submitUpload = async () => {
  if (uploadForm.value.files.length === 0) {
    return ElMessage.warning("请至少上传一张照片");
  }
  
  try {
    const formData = {
      spotId: spotId.value,
      shootTime: uploadForm.value.shootTime,
      camera: uploadForm.value.camera,
      description: uploadForm.value.description,
      imageUrls: uploadForm.value.files,
    };
    
    await service.post('/photography/works', formData);
    
    ElMessage.success("作品发布成功");
    showUploadDialog.value = false;
    
    // 重新加载照片列表
    photoParams.value.page = 1;
    await fetchSpotPhotos();
  } catch (error) {
    console.error("发布失败:", error);
    ElMessage.error("发布失败");
  }
};

// 加载更多照片
const loadMorePhotos = async () => {
  photoParams.value.page++;
  await fetchSpotPhotos();
};

// 高德地图相关
const mapContainer = ref(null);
let map = null;
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥
const mapLoaded = ref(false);

// 设置高德地图安全密钥配置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果AMap已存在且可用，直接返回
    if (window.AMap && typeof window.AMap.Map === 'function') {
      resolve(window.AMap);
      return;
    }
    
    // 清除之前可能存在的脚本，防止冲突
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]');
    if (existingScript) {
      existingScript.parentNode.removeChild(existingScript);
    }
    
    // 重置 AMap 对象，防止使用旧的实例
    if (window.AMap) {
      window.AMap = undefined;
    }
    
    // 确保安全配置已设置
    if (typeof window !== 'undefined' && !window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
    }
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    
    // 创建并加载脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.PlaceSearch&t=${timestamp}`;
    
    script.onload = () => {
      resolve(window.AMap);
    };
    
    script.onerror = (error) => {
      reject(new Error('地图加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 初始化地图
const initMap = async () => {
  try {
    // 确保地图容器存在
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 500);
      return;
    }

    // 确保地图尚未初始化
    if (map) return;

    // 加载高德地图脚本
    await loadAMapScript();

    // 再次确认DOM已经准备好
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 300);
      return;
    }

    // 创建地图实例，默认显示贵港市全貌
    map = new AMap.Map(mapContainer.value, {
      zoom: 14,
      center: [109.613196, 23.103333], // 贵港市中心坐标
      resizeEnable: true,
    });

    // 添加标记
    if (spotDetail.value.location && spotDetail.value.location.address) {
      searchSpotLocation(spotDetail.value.name, spotDetail.value.location.address);
    } else {
      // 如果没有地址信息，直接搜索景点名称
      searchSpotLocation(spotDetail.value.name, spotDetail.value.name);
    }
    
    mapLoaded.value = true;
  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};

// 搜索景点位置并添加标记
const searchSpotLocation = (title, address) => {
  if (!map || !window.AMap) return;
  
  // 创建地点搜索实例
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 1,
    pageIndex: 1,
    city: '贵港', // 限定城市
    citylimit: true,
  });

  // 优先使用完整地址搜索
  placeSearch.search(address, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
      // 获取第一个搜索结果的位置
      const position = [
        result.poiList.pois[0].location.lng,
        result.poiList.pois[0].location.lat
      ];
      
      // 添加标记
      addLocationMarker(position, title);
    } else {
      // 如果地址搜索失败，尝试使用景点名称搜索
      placeSearch.search(title, (status, result) => {
        if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          const position = [
            result.poiList.pois[0].location.lng,
            result.poiList.pois[0].location.lat
          ];
          
          addLocationMarker(position, title);
        } else {
          console.warn("未找到景点位置");
        }
      });
    }
  });
};

// 添加地点标记
const addLocationMarker = (position, name) => {
  if (!map) return;
  
  // 清除之前的标记
  map.clearMap();
  
  // 创建标记
  const marker = new AMap.Marker({
    position: position,
    title: name,
    map: map,
    icon: new AMap.Icon({
      size: new AMap.Size(40, 40),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
      imageSize: new AMap.Size(40, 40)
    }),
    offset: new AMap.Pixel(-20, -40)
  });
  
  // 设置地图中心和缩放级别
  map.setCenter(position);
  map.setZoom(15);
  
  // 创建信息窗体
  const infoWindow = new AMap.InfoWindow({
    content: `
      <div style="padding:10px;">
        <h3 style="font-weight:bold;margin-bottom:5px;">${name}</h3>
        <p style="font-size:12px;color:#666;">${spotDetail.value.location?.address || '贵港摄影打卡地'}</p>
      </div>
    `,
    offset: new AMap.Pixel(0, -30)
  });
  
  // 点击标记时显示信息窗口
  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition());
  });
  
  // 自动打开信息窗口
  infoWindow.open(map, marker.getPosition());
};

// 清理地图资源
const cleanupMap = () => {
  try {
    // 销毁地图实例
    if (map) {
      map.clearMap();
      map.destroy();
      map = null;
    }
    
    mapLoaded.value = false;
  } catch (error) {
    console.warn("清理地图资源时发生错误:", error);
  }
};

// 打开导航
const openMapNavigation = () => {
  if (!map) return;
  
  // 获取当前标记位置
  const center = map.getCenter();
  if (!center) return;
  
  // 打开高德导航
  const url = `https://uri.amap.com/navigation?to=${center.lng},${center.lat},${encodeURIComponent(spotDetail.value.name)}&mode=car&src=mypage&coordinate=gaode`;
  window.open(url, '_blank');
};

// 页面加载时获取数据
onMounted(async () => {
  fetchSpotDetail();
  
  // 确保安全配置已设置
  if (typeof window !== 'undefined') {
    window._AMapSecurityConfig = {
      securityJsCode: securityJsCode
    };
  }
  
  // 延迟初始化地图，确保DOM完全渲染
  setTimeout(() => {
    initMap();
  }, 800);
});

onBeforeUnmount(() => {
  cleanupMap();
});
</script>

<style lang="scss" scoped>
.photography-detail-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  :deep(.el-carousel) {
    .el-carousel__container {
      @apply rounded-lg;
    }

    .el-carousel__item {
      .el-image {
        @apply w-full h-full;
      }
    }
  }

  .photo-item {
    &:hover {
      .photo-info {
        @apply opacity-100;
      }
    }
  }
}
</style>
